/**
 * http://usejsdoc.org/
 */
var res,req,
	fs = require('fs'),
	url = require('url'),
	querystring = require('querystring'),
	httpParam = require('./http_param'),
	BASE_DIR = __dirname;

/**创建初始变量函数*/
exports.init = function(response,request){
	res = response;
	req = request;
	httpParam.init(res,req);
};

/**
 * 文件删除操作
 */
exports.del = function(){
	var file = httpParam.GET('file');
	fs.exists(BASE_DIR + '/file_test/'+file, function(existBool){
		if(existBool){
			var ret = '';
			fs.unlink(BASE_DIR + '/file_test/'+file, function(err){
				if(err){
					ret = err;
				}else{
					ret = 'delete file success!';
				}
				res.writeHead( 200 , {"Content-Type":"text/plain"});
				res.end(ret);
			});
		}else{
			res.writeHead( 200 , {"Content-Type":"text/plain"});
			res.end('not exist file');
		}
	});
};

/**
 * 文件读取操作
 */
exports.reader = function(){
	var folder = httpParam.GET('folder');
	fs.exists(BASE_DIR + '/'+folder, function(existBool){
		if(existBool){
			var ret = '';
			fs.readdir(BASE_DIR + '/'+folder, function(err,files){
				if(err){
					ret = err;
				}else{
					ret = JSON.stringify(files);
				}
				res.writeHead( 200 , {"Content-Type":"text/plain"});
				res.end(ret);
			});
		}else{
			res.writeHead( 404 , {"Content-Type":"text/plain"});
			res.end('404 not found!');
		}
	});
};

exports.writer = function(){
	var folder = httpParam.GET('folder'),fileName =httpParam.GET('fileName'),content=httpParam.GET('content');
	fs.exists(BASE_DIR + '/'+folder, function(existBool){
		var ret = '';
		if(existBool){
			fs.open(BASE_DIR + '/'+ folder +'/'+fileName, 'a', function(err,fd){
				 if(err){
					 ret = err;
				 }
				 fs.write(fd, "\n"+content, 0,'utf8', function(err,written,String){
					if (err) {
						ret = err;
					}else{
						ret = 'message write success!';
					}
				 });
				 fs.close(fd,function(err){
					if (err) {
						ret = err;
					}
				 });
				 res.writeHead( 200 , {"Content-Type":"text/plain"});
				 res.end(ret);
			});
		}else{
			res.writeHead( 404 , {"Content-Type":"text/plain"});
			res.end('404 not found!');
		}
		
	});
};
